package com.example.android.codelabs.navigation

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import entity.UserInfo
import java.io.FileNotFoundException

class UserFragment: Fragment() {
    private lateinit var ivUserAvatar: ImageView
    private lateinit var btnUploadAvatar: Button
    private lateinit var tvUserNickname: TextView
    private lateinit var btnEditNickname: Button
    private val PICK_IMAGE_REQUEST = 1
    private lateinit var userInfo: UserInfo
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.activity_my_user, container, false)

        ivUserAvatar = view?.findViewById<ImageView>(R.id.iv_user_avatar)!!
        btnUploadAvatar = view?.findViewById<Button>(R.id.btn_upload_avatar)!!
        tvUserNickname= view?.findViewById<TextView>(R.id.tv_user_nickname)!!
        btnEditNickname = view?.findViewById<Button>(R.id.btn_edit_nickname)!!
        userInfo = UserInfo()
        // 设置初始显示的昵称
        tvUserNickname.text = "昵称：${userInfo.getNickname()}"

        // 上传头像按钮点击事件
        btnUploadAvatar.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent, PICK_IMAGE_REQUEST)
        }

        // 修改昵称按钮点击事件
        btnEditNickname.setOnClickListener {
            // 这里可以弹出一个对话框或者跳转到另一个页面来修改昵称
            // 为了简化示例，这里只是模拟修改
            userInfo.setNickname("新昵称")
            tvUserNickname.text = "昵称：${userInfo.getNickname()}"

        }
        return view


    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data!= null) {
            val imageUri = data.data
            try {

                var huanan=imageUri?.let { uri ->
                    requireActivity().contentResolver.openInputStream(uri)
                }
                val bitmap = BitmapFactory.decodeStream(huanan)
                userInfo.setAvatar(bitmap)
                ivUserAvatar.setImageBitmap(bitmap)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
        }
    }


}